<template>
  <div class="addFormula">
    <!-- 公式设置 -->
    <el-dialog :visible.sync="dialogVisible" lock-scroll width="750px" title="扩展计算公式">
      <div class="for-content">
        <div v-if="replaceProps" style="width: 150px;height: 100%;border-right: #efefef 1px solid;overflow: hidden;overflow-y: scroll">
          <div style="display: flex;justify-content: space-between;align-items: center;height: 50px;font-size: 13px;padding: 0 5px;">
            <div>请选择新的字段</div>
            <div style="color: #409EFF;cursor: pointer;" @click="replaceCancel">取消</div>
          </div>
          <div v-for="item in replaceList" :key="item.props" class="sourceItem" @click="replaceFormula(item)">
            <span v-if="item.disabled" style="color: #ddd;">{{ item.text }}</span>
            <span v-else>{{ item.text }}</span>
          </div>
        </div>
        <div v-else style="width: 150px;height: 100%;border-right: #efefef 1px solid;overflow: hidden;overflow-y: scroll">
          <div v-for="item in sourceList" :key="item.props" class="sourceItem" @click="addFormulaBySource(item)" :style="item.selected ? 'background-color: #E3F6FF;' : '' ">
            <span v-if="item.disabled" style="color: #ddd;">{{ item.text }}</span>
            <span v-else>{{ item.text }}</span>
            <i v-if="item.selected" class="el-icon-check" style="color: #409EFF;"></i>
          </div>
        </div>
        <div style="width: 30px;background-color: #409EFF;margin: 30px 10px;height: 20px;line-height: 20px;text-align: center;color:white;font-size: 18px;border-radius: 3px;">>></div>
        <div style="flex: 1;border-left: #efefef 1px solid;">
          <div class="header">计算公式</div>
          <div class="for-show">
            <span v-if="formulaList.length == 0" style="color: #999;">请选择</span>
            <span v-for="(item,index) in formulaList" :key="index" style="height: 20px;" :style="constList.includes(item.props) ? 'cursor: pointer;' : '' " @click="replaceClick(item)">
              <span :style="(replaceProps && item.props == replaceProps) ? 'background-color: #409EFF;color:white;border-radius:2px;' : ''">{{ item.text }}</span>
            </span>
          </div>
          <div class="header">数字运算符</div>
          <div style="display: flex;justify-content: space-between;font-weight: 500;position: relative;" :style="replaceProps ? 'color:#999;' : ''">
            <div style="left: 0;right: 0;top: 0;bottom: 0;position: absolute;" v-if="replaceProps"></div>
            <div style="display: flex;width: 270px;flex-wrap: wrap;padding: 10px;">
              <div v-for="item in [1,2,3,4,5,6,7,8,9,0,'.','00']" :key="item" class="numberItem" @click="addFormula(item)">
                {{  item }}
              </div>
            </div>
            <div style="display: flex;width: 200px;flex-wrap: wrap;padding: 10px;align-items: flex-start;">
              <div v-for="item in ['+','-','*','/','=']" :key="item" class="numberItem"  @click="addFormula(item)">
                {{  item }}
              </div>
              <div class="numberItem" style="width: 30px;" @click="addFormula('(')">(</div>
              <div class="numberItem" style="width: 30px;" @click="addFormula(')')">)</div>
              <div class="numberItem" style="color: #409EFF;" @click="clearFormula(1)">撤销</div>
              <div class="numberItem" style="color: #FD6C21;" @click="clearFormula(0)">清空</div>
            </div>
          </div>
        </div>
      </div>
      <div class="dialog_bottom">
          <el-button type="primary" size="small" @click.stop="onFormulaConfirm">保存</el-button>
          <el-button size="small" @click.stop="hideSet">取消</el-button>
        </div>
    </el-dialog>
    <!-- 新增公式名称 -->
    <el-dialog title="新增计算公式名称" :visible.sync="addFormulaVisible" width="400px">
        <div class="extendView">
          <div class="title">公式名称</div>
          <el-input v-model="formulaName" size="mini" placeholder="请输入" clearable></el-input>
        </div>
        <div class="dialog_bottom">
          <el-button type="primary" size="small" @click.stop="onFormulaNameConfirm">保存</el-button>
          <el-button size="small" @click.stop="hideAddName">取消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID, USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import { getAction, postAction, putAction } from '../../api/manage'
import { handleObjectToArray } from '../../utils'
export default {
  name: 'dialogFormula',
  computed: {
    ...mapGetters(['name']),
  },
  created() {},
  updated() {},
  data() {
    return {
      goodsId: '',
      formulaId: '',
      replaceProps: '',
      replaceList: [],
      constList: ['number', 'salePrice', 'discountUnitPrice', 'discountRate', 'taxRate', 'taxPrice', 'allPrice', 'norms', 'salePrice', 'extendField1', 'extendField2', 'extendField3', 'extendField4', 'extendField5', 'extendValue1', 'extendValue2', 'extendValue3', 'extendValue4', 'extendValue5'],
      sourceList: [
        {
          text: '数量',
          props: 'number',
          disabled: false,
          selected: false
        },
        {
          text: '单价',
          props: 'salePrice',
          disabled: false,
          selected: false
        },
        {
          text: '折扣单价',
          props: 'discountUnitPrice',
          disabled: false,
          selected: false
        },
        {
          text: '折扣率',
          props: 'discountRate',
          disabled: false,
          selected: false
        },
        {
          text: '税率',
          props: 'taxRate',
          disabled: false,
          selected: false
        },
        {
          text: '税额',
          props: 'taxPrice',
          disabled: false,
          selected: false
        },
        {
          text: '金额',
          props: 'allPrice',
          disabled: false,
          selected: false
        },
        {
          text: '规格',
          props: 'norms',
          disabled: false,
          selected: false
        }
      ],
      formulaList: [],

      dialogVisible: false, // 新增弹框
      formulaModel: {},

      //公式名称
      addFormulaVisible: false,
      formulaName: '',
    }
  },
  watch: {
    formulaList(val, s) {
      let equal = val.find(item => item.props == '=')
      if (equal) {
        for (let index = 0; index < this.sourceList.length; index++) {
          let element = this.sourceList[index];
          element.disabled = !element.props.includes('extendValue')
          element.selected = this.getItemSelect(element)
        }
      } else {
        for (let index = 0; index < this.sourceList.length; index++) {
          let element = this.sourceList[index];
          element.disabled = element.props.includes('extendValue')
          element.selected = this.getItemSelect(element)
        }
      }
    }
  },
  methods: {
    getItemSelect(ele) {
      let sel = this.formulaList.find(item => item.props == ele.props)
      if (sel) {
        return true
      } else {
        return false
      }
    },
    showSet(item, columns) {
      this.formulaModel = item
      this.formulaList = []
      this.replaceCancel()
      let list = []
      for (let index = 1; index < 6; index++) {
        let key = 'extendField' + index
        let column = columns[key]
        if (column) {
          let name = column.zidingyiName || column.morenName
          list.push({
            text: name,
            props: column.props,
            disabled: false,
            selected: false
          })
        }
      }
      for (let index = 1; index < 6; index++) {
        let key = 'extendValue' + index
        let column = columns[key]
        if (column) {
          let name = column.zidingyiName || column.morenName
          list.push({
            text: name,
            props: column.props,
            disabled: true,
            selected: false
          })
        }
      }
      let sl = this.$options.data().sourceList
      this.sourceList = sl.concat(list)

      if (item.formulaJson) {
        let json = JSON.parse(item.formulaJson)
        this.formulaList = json.map(fItem => {
          let ad = this.sourceList.find(sItem => sItem.props == fItem.props)
          return {
            props: fItem.props,
            text: ad ? ad.text : fItem.text
          }
        })
      }

      this.dialogVisible = true
    },
    hideSet() {
      this.dialogVisible = false
    },
    showAddName(goodsId) {
      this.goodsId = goodsId
      this.formulaName = ''
      this.addFormulaVisible = true
    },
    hideAddName() {
      this.addFormulaVisible = false
    },
    addFormulaBySource(item) {
      if (!item.disabled && !item.selected) {
        this.formulaList.push({
          text: item.text,
          props: item.props
        })
      }
    },
    addFormula(text) {
      this.formulaList.push({
        text,
        props: text
      })
    },
    clearFormula(type) {
      if (type == 0) { //清空
        this.formulaList = []
      } else if (this.formulaList.length > 0) { //撤销
        this.formulaList.splice(this.formulaList.length - 1, 1)
      }
    },
    // 新增公式名称提交
    onFormulaNameConfirm() {
      if (!this.formulaName) {
        return this.$message.error('请输入公式名称!')
      } 
      let params = {
        name: this.formulaName,
        goodsId: this.goodsId
      }
      postAction('/xghGoodsExtendFormula/xghGoodsExtendFormula/add', params).then(res => {
        console.log(res);
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('updateFormula', this.goodsId)
          this.hideAddName()
        } else {
          this.$message.error(res.message)
        }

      })
    },
    // 设置公式提交
    onFormulaConfirm() {
      if (this.formulaList.length == 0) {
        return this.$message.error('请设置公式!')
      } 
      let formula = this.formulaList.map(item => {
        return item.text
      }).join('')
      let params = {
        id: this.formulaModel.id,
        goodsId: this.formulaModel.goodsId,
        name: this.formulaModel.name,
        formula,
        formulaJson: JSON.stringify(this.formulaList)
      }
      putAction('/xghGoodsExtendFormula/xghGoodsExtendFormula/updateFormula', params).then(res => {
        console.log(res);
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('updateFormula', this.formulaModel.goodsId)
          this.hideSet()
        } else {
          this.$message.error(res.message)
        }

      })
    },
    replaceClick(item) {
      if (!this.constList.includes(item.props)) {
        return
      }
      this.replaceProps = item.props
      let isResult = item.props.includes('extendValue')
      let list = JSON.parse(JSON.stringify(this.sourceList))
      this.replaceList = list.map(ele => {
        let index = this.formulaList.findIndex(obj => obj.props == ele.props)
        ele.disabled = index > -1
        if (isResult && ele.props.includes('extendValue')) {
          return ele
        } else if (!isResult && !ele.props.includes('extendValue')) {
          return ele
        }
      }).filter(ele => ele)
      console.log(this.replaceList);
      
    },
    replaceFormula(item) {
      if (item.disabled) {
        return
      }
      let index = this.formulaList.findIndex(ele => ele.props == this.replaceProps)
      console.log(index);
      
      this.formulaList.splice(index, 1, item)
      this.replaceProps = ''
    },
    replaceCancel() {
      this.replaceProps = ''
    }
  },
}
</script>

<style lang="scss" scoped>

::v-deep .el-dialog__header {
  border-bottom: #efefef 1px solid;
}
.addFormula {
  ::v-deep .el-dialog {
    .el-dialog__body {
      padding: 10px 30px;
    }
  }
}

.for-content {
  margin-top: 10px;
  width: 100%;
  height: 430px;
  border: #efefef 1px solid;
  display: flex;
}

.sourceItem {
  padding:0 10px;
  height: 25px;
  font-size: 12px;
  color: #666666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}
.header {
  height: 30px;
  background: #EDEDED;
  color: #000;
  padding-left: 10px;
  font-weight: 500;
  line-height: 30px;
}
.for-show {
  border: #efefef 1px solid;
  border-radius: 5px;
  height: 150px;
  margin: 15px 20px;
  padding: 5px 10px;
  color: #666;
  display: flex;
  flex-wrap: wrap;
}
.numberItem {
  width: 70px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: #efefef 1px solid;
  border-radius: 5px;
  margin: 5px;
  cursor: pointer;
}


.extendView {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80px;

    .title {
      flex-shrink: 0;
      margin-right: 10px;
    }
  }
  .dialog_bottom {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 80px;
    }
  }
</style>
